#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "share_info.h"

int g_main_data;
int* g_main_ptr;

void InitMain() {
	g_main_data = 'M';
	g_main_ptr = &g_main_data;
}

info_t* GetMainInfo() {
	static info_t share;
	SetData(&share);
	return &share;
}

int DiffVal(char* s1name, char* s2name, char* typename, int v1, int v2) {
	if (v1 != v2) {
		printf("%s value from %s=%d, from %s=%d!\n", typename, s1name, v1, s2name, v2);
		return 1;
	}
	return 0;
}

int DiffPtr(char* s1name, char* s2name, char* typename, int* v1, int* v2) {
	if (v1 != v2) {
		printf("%s ptr from %s=%x, from %s=%x!\n", typename,
					 s1name, v1, s2name, v2);
		return 1;
	}
	return 0;
}

void Compare(char* s1name, info_t* s1, char* s2name, info_t* s2) {
	int fails = 0;
	
	fails += DiffVal(s1name, s2name, "share", s1->share_val, s2->share_val);
	fails += DiffVal(s1name, s2name, "main", s1->main_val, s2->main_val);

	fails += DiffPtr(s1name, s2name, "share loc", s1->share_loc, s2->share_loc);
	fails += DiffPtr(s1name, s2name, "main loc", s1->main_loc, s2->main_loc);

	fails += DiffPtr(s1name, s2name, "share ptr", s1->share_ptr_val, s2->share_ptr_val);
	fails += DiffPtr(s1name, s2name, "main ptr", s1->main_ptr_val, s2->main_ptr_val);

	fails += DiffPtr(s1name, s2name, "share ptr loc", *s1->share_ptr_loc, *s2->share_ptr_loc);
	fails += DiffPtr(s1name, s2name, "main ptr loc", *s1->main_ptr_loc, *s2->main_ptr_loc);
	if (fails > 0) {
	  printf("FAILED %s <-> %s!\n", s1name, s2name);
		exit(1);
	}
	printf("Passed %s <-> %s.\n", s1name, s2name);
}

int main(int argc, char* argv[]) {
	InitMain();
	InitOther();
	InitShare();

	info_t* main = GetMainInfo();
	info_t* share = GetShareInfo();
	info_t* other = GetOtherInfo();

	Compare("main info", main, "share data", share);
	Compare("main info", main, "other data", other);
  return 0;
}
